﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using eCRAM.WebSite.Models;
using eCRAM.Bll;
using eCRAM.Model;
using eCRAM.WebSite.Services;

namespace eCRAM.WebSite.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {

        private User _currentUser;

        //Account controller has a dependency with IRepository (interface not instance)
        public IUserManager _userRepo = null;

        //Account controller has a dependency with  HttpSessionStateBase (base class not instance)
        ISession _session = null;

        private readonly IAuthenticationService _service;

        public IFormsAuthenticationService FormsAuth
        {
            get;
            private set;
        }


        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public AccountController(IFormsAuthenticationService formsAuth, IAuthenticationService service, IUserManager userRepo, ISession session)
        {
            FormsAuth = formsAuth;
            _service = service;
            _userRepo = userRepo;
            _session = session;
        }
        
        
       
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult LogOn()
        {
            return View();
        }

        /// <summary>
        /// Called when the user entered its username and password.
        /// </summary>
        /// <param name="userName">Login</param>
        /// <param name="password">Password</param>
        /// <param name="rememberMe">Remember or not the session inside the web browser via a cookie</param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
                                                         Justification = "Needs to take same parameter type as Controller.Redirect()")]
        public ActionResult LogOn(string userName, string password, bool rememberMe)
        {
            if (!ValidateLogOn(userName, password))
            {
                return View();
            }

            FormsAuth.SignIn(userName, rememberMe);
            return RedirectToAction("Index", "Home");
        }



        /// <summary>
        /// Checks the username and password are correct.
        /// </summary>
        /// <param name="userName">Login</param>
        /// <param name="password">Password</param>
        /// <returns>True in case the username and password are valid; false otherwise</returns>
        private bool ValidateLogOn(string userName, string password)
        {
            try
            {
                if (String.IsNullOrEmpty(userName))
                    ModelState.AddModelError("userName", "You must specify a username.");
                if (String.IsNullOrEmpty(password))
                    ModelState.AddModelError("password", "You must specify a password.");
                else
                {
                    _currentUser = _service.LogOn(userName, password);
                    if (_currentUser == null)
                        ModelState.AddModelError("_FORM", "The username or password provided is incorrect.");
                    else if (!_currentUser.IsActive)
                        ModelState.AddModelError("_FORM", "Your account is disabled.");
                }

                //FIXME
                SessionData session = new SessionData
                {
                    CurrentUser = _currentUser
                };

                _session["MySessionData"] = session;

                return ModelState.IsValid;
            }
            catch (ApplicationException exc)
            {
                throw exc;
            }
        }


        // **************************************
        // URL: /Account/LogOff
        // **************************************

        /// <summary>
        /// Logs off the current user.
        /// </summary>
        /// 
        /// <remarks>
        /// Called by LogOnUserControl.ascx (the view).
        /// </remarks>
        /// 
        /// <returns></returns>
        public ActionResult LogOff()
        {
            FormsAuth.SignOut();

            return RedirectToAction("Index", "Home");
        }
        // **************************************
        // URL: /Account/Register
        // **************************************
/*
        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Tentative d'inscription de l'utilisateur
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsService.SignIn(model.UserName, false );
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // Si nous sommes arrivés là, quelque chose a échoué, réafficher le formulaire
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "Le mot de passe actuel est incorrect ou le nouveau mot de passe n'est pas valide.");
                }
            }

            // Si nous sommes arrivés là, quelque chose a échoué, réafficher le formulaire
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }
*/

    }
}
